<?php
/**
 * @Author: gan
 * @Description:
 * @File:  HdImpl
 * @Version: 1.0.0
 * @Date: 2023/3/28 8:58 上午
 */
declare(strict_types=1);

namespace RX\Component\Sms\Impl;

use RX\Enums\SmsEnum;
use RX\Exception\BizException;
use RX\Helpers\RandomHelper;
use RX\Helpers\StringHelper;
use RX\Traits\CurlTrait;

class HdImpl implements SmsInterface
{
    use CurlTrait;

    private string $url;
    private string $appKey;
    private string $appCode;
    private string $appSecret;

    public function __construct(array $config = [])
    {
        if (empty($config)) {
            $config = StringHelper::config('sms.hd');
        }
        $this->url       = $config["url"];
        $this->appKey    = $config["appKey"];
        $this->appCode   = $config["appCode"];
        $this->appSecret = $config["appSecret"];
    }

    public function send(string $mobile, string $sign, string $template, array $templateParams = [])
    {
        $timestamp = RandomHelper::makeMillisecond();
        $apiSign   = strtolower(md5($this->appKey . $this->appSecret . $timestamp));
        $data      = [
            'appkey'    => $this->appKey,
            'appcode'   => $this->appCode,
            'timestamp' => $timestamp,
            'sign'      => $apiSign,
            'phone'     => $mobile,
            'msg'       => $sign . $template
        ];

        $result = $this->postCurl($this->url, $data);
        $result = json_decode($result, true);
        if (!isset($result['code']) || $result['code'] != '00000') {
            throw new BizException(SmsEnum::class, SmsEnum::SMS_FAIL, ($result['desc'] ?? null));
        }
        return $result;
    }
}
